package com.iot.comprehensive.face.controller;

import com.iot.comprehensive.face.dto.AccessFormDto;
import com.iot.comprehensive.face.dto.AccessInfo;
import com.iot.comprehensive.face.model.AccessForm;
import com.iot.comprehensive.face.model.Account;
import com.iot.comprehensive.face.service.AccessFormService;
import com.iot.comprehensive.face.service.AccountService;
import com.iot.comprehensive.face.service.UserService;
import com.iot.comprehensive.face.utils.*;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 朱泽玉
 * @Create 2021/6/27 16:54
 * @Description
 * @Modified By:
 */
@RestController
@RequestMapping("/access")
@Api(tags = "申请单操作", protocols = "http,https")
@ApiResponses({
        @ApiResponse(code = 200, message = "登录成功"),
        @ApiResponse(code = 300, message = "出现错误"),
        @ApiResponse(code = 301, message = "无权限(未认证)")
})
public class AccessFormController {
    //    @Autowired
    final AccessFormService accessFormService;
    final AccountService accountService;
    final UserService userService;
    @Autowired
    private Jwt jwt;

    public AccessFormController(AccessFormService accessFormService, AccountService accountService, UserService userService) {
        this.accessFormService = accessFormService;
        this.accountService = accountService;
        this.userService = userService;
    }

    /**
     * 根据header获取访问表
     * user：我申请的
     * host：我处理的
     * admin：全部
     * @return 所对应的访问表
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部访问表", notes = "根据header，返回对应的访客表")
    public Result all(HttpServletRequest request) throws IOException {
        // 1、获取返回的token
        Claims token = jwt.token(request);
        // 2、判断是否携带token
        if (token == null) {
            return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
        }
        // 3、获取token中的id值
        Long id = Long.valueOf(token.getId());
        // 4、查看对应的身份
        String identity = accountService.findById(id).getIdentity();
        if (identity.equals("user")){
            List<AccessForm> accessFormList = accessFormService.findByUserId(id);
            for (AccessForm accessForm : accessFormList) {
                String host_mobile = accountService.findById(accessForm.getHost_id()).getMobile();
                accessForm.setHost_id(Long.parseLong(host_mobile));
            }
            return new Result(ResultCode.SUCCESS, accessFormList);
        }
        if (identity.equals("host")){
            //1、根据住户id获取全部审批表
            List<AccessForm> accessFormList = accessFormService.findByHostId(id);
            //2、修改审批表返回的user_id修改为user的手机号码
            for (AccessForm accessForm : accessFormList) {
                String host_mobile = accountService.findById(accessForm.getUser_id()).getMobile();
                accessForm.setHost_id(Long.parseLong(host_mobile));
            }
            return new Result(ResultCode.SUCCESS, accessFormList);
        }
        if (identity.equals("admin")){
            List<AccessForm> accessFormList = new ArrayList<>();
            List<AccessInfo> accessInfoList = new ArrayList<>();
            accessFormList = accessFormService.findAll();
            for (AccessForm accessForm:accessFormList){
                long user_account_id = accessForm.getUser_id();
                long host_account_id = accessForm.getHost_id();
                AccessInfo accessInfo = new AccessInfo();
                accessInfo.setAccessForm(accessForm);
                accessInfo.setHost_account(accountService.findById(host_account_id));
                accessInfo.setApproval_account(accountService.findById(user_account_id));
                accessInfo.setApproval(userService.getByAccount(user_account_id));
                accessInfo.setHost(userService.getByAccount(host_account_id));
                accessInfoList.add(accessInfo);
            }
            return new Result(ResultCode.SUCCESS, accessInfoList);
        }
        return new Result(ResultCode.UN_LOGIN);
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ApiOperation(value = "添加访问表", notes = "添加访问表")
    public Result add(HttpServletRequest request,
                      @RequestBody AccessFormDto accessForm) {
        try {
            // 1、获取返回的token
            Claims token = jwt.token(request);
            // 2、判断是否携带token
            if (token == null) {
                return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
            }
            // 4、获取token中的id值
            Long id = Long.valueOf(token.getId());
            Account account = accountService.findByMobile(accessForm.getHost_mobile());
            Long host_id = account.getId();
            if (!account.getIdentity().equals("host")){
                return new Result(ResultCode.FAIL,"住户手机号错误");
            }
            AccessForm accessForm1 = new AccessForm();
            accessForm1.setState(0);
            // 如果是用户自身申请的临时码，修改状态进行添加
            String code = "";
            if (host_id.equals(id)){
                code = SnowflakeIdWorker.getAccessId();
                accessForm1.setState(1);
                accessForm1.setAccessCode(code);
            }
            accessForm1.setStart_time(PatternUtils.GetTime());
            accessForm1.setFinish_time(accessForm.getFinish_time());
            accessForm1.setHost_id(host_id);
            accessForm1.setUser_id(id);
            accessFormService.add(accessForm1);
            return new Result(ResultCode.SUCCESS,code);
        } catch (Exception e) {
            return new Result(ResultCode.FAIL);
        }
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "获取单个表", notes = "获取单个表")
    public Result byId(@PathVariable("id") int id, HttpServletRequest request) {
        try {
            return new Result(ResultCode.SUCCESS, accessFormService.findById(id));
        } catch (Exception e) {
            return new Result(ResultCode.FAIL);
        }
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ApiOperation(value = "更新访问表", notes = "根据header自动识别并进行更新")
    public Result update(@PathVariable("id") int accessId,
                         HttpServletRequest request,
                         @RequestBody AccessFormDto accessFormDto) {
        try {
            // 创建提交对象
            AccessForm accessForm = accessFormService.findById(accessId);
            // 1、获取返回的token
            Claims token = jwt.token(request);
            // 2、判断是否携带token
            if (token == null) {
                return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
            }
            // 如果已经过期
            if (accessForm.getState()==2){
                //不允许进行修改
                return new Result(ResultCode.FAIL, "过期不允许修改");
            }
            System.out.println(PatternUtils.getNumb(accessForm.getFinish_time()));
            System.out.println(PatternUtils.getNumb(PatternUtils.GetTime()));
            if (Long.parseLong(PatternUtils.getNumb(accessForm.getFinish_time()))<Long.parseLong(PatternUtils.getNumb(PatternUtils.GetTime()))){
                accessForm.setState(2);
                accessFormService.add(accessForm);
            }
            // 3、获取token中的id值
            Long id = Long.valueOf(token.getId());
            // 4、判断是什么角色的提交
            String identity = accountService.findById(id).getIdentity();
            if (identity.equals("user")) {
                // 设置过期时间
                accessForm.setFinish_time(accessFormDto.getFinish_time());
                // 标记为审批阶段
                accessForm.setState(0);
            }
            if (identity.equals("host")) {
                // 标记为已经通过审批
                if (accessFormDto.getPass()==1){
                    accessForm.setAccessCode(SnowflakeIdWorker.getAccessId());
                    accessForm.setState(1);
                }
                // 标记为未通过
                else if (accessFormDto.getPass()==3){
                    accessForm.setState(3);
                }
                accessForm.setSuggest(accessFormDto.getSuggest());
            }
            if (identity.equals("admin")) {
                // 填写管理员编号
                accessForm.setAdmin_id(id);
                // 标记为已经完成最终处理
                accessForm.setState(2);
                // 设置过期时间
                accessForm.setFinish_time(accessFormDto.getFinish_time());
            }
            accessFormService.add(accessForm);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            return new Result(ResultCode.FAIL);
        }
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除表", notes = "只允许普通用户删除未审批，允许住户删除所有向自己申请的，管理员不允许删除")
    public Result delete(@PathVariable("id") int access_id, HttpServletRequest request) {
        try {
            // 1、获取返回的token
            Claims token = jwt.token(request);
            // 2、判断是否携带token
            if (token == null) {
                return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
            }
            // 3、获取token中的id值
            Long id = Long.valueOf(token.getId());
            // 4、获取请求用户身份
            String identity = accountService.findById(id).getIdentity();
            // 普通用户的话查看该申请表是否是自己的，并且状态需要是未审核
            if (identity.equals("user")){
                AccessForm accessForm = accessFormService.findById(access_id);
                if (accessForm.getUser_id().equals(id)&&accessForm.getState()==0){
                    accessFormService.del(access_id);
                    return new Result(ResultCode.SUCCESS);
                }
                return new Result(ResultCode.UN_AUTHORISE,"无权删除");
            }
            // 住户的话需要判断是否是自己的，只要是就能删除
            if (identity.equals("host")){
                AccessForm accessForm = accessFormService.findById(access_id);
                if (accessForm.getHost_id().equals(id)){
                    accessFormService.del(access_id);
                    return new Result(ResultCode.SUCCESS);
                }
                return new Result(ResultCode.UN_AUTHORISE,"无权删除");
            }
            return new Result(ResultCode.FAIL);
        } catch (Exception e) {
            return new Result(ResultCode.FAIL);
        }
    }

    @RequestMapping(value = "/available", method = RequestMethod.GET)
    @ApiOperation(value = "获取可用码", notes = "获取可用码")
    public Result byId(HttpServletRequest request) {
        try {
            // 1、获取返回的token
            Claims token = jwt.token(request);
            // 2、判断是否携带token
            if (token == null) {
                return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
            }
            // 3、获取token中的id值
            Long id = Long.valueOf(token.getId());
            List<AccessForm> accessForm = accessFormService.findAvailable(id);
            return new Result(ResultCode.SUCCESS, accessForm);
        } catch (Exception e) {
            return new Result(ResultCode.FAIL);
        }
    }

}


